#include "delayedParse.h"
#include "globals.h"     // 访问 exit_flag/g_latestPacket 等
#include <thread>
#include <iostream>
#include <cstring>        // for memcpy
#include <sys/time.h>     // gettimeofday

// 定义固定延时 300ms
const int FIXED_DELAY_MS = 300;

// 可选：定义最大队列长度 10 (示例)
const size_t MAX_QUEUE_SIZE = 10;

// 定义全局队列与互斥量
std::queue<DelayedPacket> g_delayQueue;
std::mutex g_delayQueueMutex;
std::condition_variable g_delayQueueCV;

/**
 * @brief 将包推入队列，如果队列超过 MAX_QUEUE_SIZE 则丢包
 */
void pushPacketWithDrop(const DelayedPacket &dp)
{
    std::lock_guard<std::mutex> lk(g_delayQueueMutex);
    if (g_delayQueue.size() >= MAX_QUEUE_SIZE) {
        // 丢弃老包 or 丢弃新包 任选其一
        // 这里示例“丢弃最旧的包”:
        g_delayQueue.pop();
        std::cerr << "[pushPacketWithDrop] Queue Full => Dropped oldest packet.\n";
    }
    g_delayQueue.push(dp);
    g_delayQueueCV.notify_one();
}

void delayedParseThreadFunc()
{
    while (!exit_flag) {
        DelayedPacket dp;

        {
            std::unique_lock<std::mutex> lk(g_delayQueueMutex);
            if (g_delayQueue.empty()) {
                // 无数据 => 等待
                g_delayQueueCV.wait_for(lk, std::chrono::milliseconds(50));
                if (exit_flag) break;
                continue;
            }

            dp = g_delayQueue.front();
            g_delayQueue.pop();
        }

        // 计算目标处理时间 = arrivalTime + FIXED_DELAY_MS
        auto targetTime = dp.arrivalTime + std::chrono::milliseconds(FIXED_DELAY_MS);
        auto now = std::chrono::steady_clock::now();
        if (now < targetTime) {
            std::this_thread::sleep_until(targetTime);
        }

        // 解析 packet, 并写入 [40..43] = delay_ms (示例)
        std::vector<unsigned char> packet = dp.data;

        // (1) 读取 send_ts
        uint32_t send_ts = 0;
        if (packet.size() >= 36) {
            memcpy(&send_ts, &packet[32], 4);
        }

        // (2) 获取当前 local_ms (一天中的毫秒)
        struct timeval tv;
        gettimeofday(&tv, nullptr);
        time_t raw_time = tv.tv_sec;
        struct tm local_tm;
        localtime_r(&raw_time, &local_tm);
        uint32_t local_ms = (uint32_t)local_tm.tm_hour*3600000U
                          + (uint32_t)local_tm.tm_min *60000U
                          + (uint32_t)local_tm.tm_sec *1000U
                          + (uint32_t)(tv.tv_usec/1000U);

        // (3) 计算实际延时
        int32_t delay_ms = (int32_t)local_ms - (int32_t)send_ts;

        // (4) packet扩大到44字节，写入 [40..43]
        if (packet.size() < 44) {
            packet.resize(44, 0x00);
        }
        memcpy(&packet[40], &delay_ms, sizeof(int32_t));

        // 处理完 => 放到全局最新包
        {
            std::lock_guard<std::mutex> lk(g_latestMutex);
            g_latestPacket = packet;
            g_hasNewPacket.store(true);
        }

        // debug
        // std::cout << "[delayedParseThreadFunc] Done with ~" << FIXED_DELAY_MS << "ms.\n";
    }

    std::cout << "[delayedParseThreadFunc] exit.\n";
}
